import { LPAPIFactory, LPAUtils } from "../../utils/lpapi-ble/index";
// 注意：微信小程序本身不支持 xml 解析功能，用户可以使用任何符合规范的DOMParser解析工具；
// 当前所用的 dom解析工具是：https://github.com/jindw/xmldom；
import { DOMParser } from "../../utils/libs/dom-parser";
import { wdfxStr } from "./datas";
import tool from '../../modules/tool'
//获取应用实例
// var app = getApp();
Page({
  data: {
    canvasId: "lpapi-ble-wx",
    labelWidth: 960,
    labelHeight: 960,
    deviceList: [{ name: "未检测到打印机", deviceId: "" }],
    deviceIndex: 0,
    orientationList: [
      { name: "横向打印", value: 0 },
      { name: "右转90度", value: 90 },
      { name: "旋转180度", value: 180 },
      { name: "左转90度", value: 270 },
    ],
    orientationIndex: 0,
    gapList: [
      { name: "随打印机设置", value: 255 },
      { name: "小票纸", value: 0 },
      { name: "不干胶", value: 2 },
      { name: "卡纸", value: 3 },
    ],
    gapIndex: 0,
    darknessList: [
      { name: "随打印机设置", value: 255 },
      { name: "6 (正常)", value: 6 },
      { name: "7", value: 7 },
      { name: "8", value: 8 },
      { name: "9", value: 9 },
      { name: "10 (较浓)", value: 10 },
      { name: "11", value: 11 },
      { name: "12", value: 12 },
      { name: "13", value: 13 },
      { name: "14", value: 14 },
      { name: "15 (最浓)", value: 15 },
    ],
    darknessIndex: 0,
    speedList: [
      { name: "随打印机设置", value: 255 },
      { name: "最慢", value: 1 },
      { name: "较慢", value: 2 },
      { name: "正常", value: 3 },
      { name: "较快", value: 4 },
      { name: "最快", value: 5 },
    ],
    speedIndex: 0,
    printModes: [
      { title: "打印", value: 0 },
      { title: "预览", value: 1, checked: true },
    ],
    printMode: 1,
    previewImage: "",
    previewList: [],
    threshold: 150,
  },
  async onLoad() {
    console.log(`========== onLoad ==========`);
    // 可以不指定Canvas，此时会使用离屏Canvas进行标签绘制操作；
    // this.initApi();

    setTimeout(() => {
      this.textPrintTest()
    }, 100);

  },
  async onReady() {
    console.log(`========== onReady ==========`);
    // const query = wx.createSelectorQuery();
    // query
    //     .select(`#${this.data.canvasId}`)
    //     .fields({ node: true, size: true })
    //     .exec((res) => {
    //         console.log(`---- querySelector(${this.data.canvasId}) ----`);
    //         console.log(res);
    //         const canvas = res[0].node;
    //         this.initApi(canvas);
    //     });
    this.initApi();
  },
  onHide() {
    // 页面隐藏
    this.closePrinter();
  },
  handleChangeMode0() {
    this.setData({
      printMode: 0
    })
  },
  handleChangeMode1() {
    this.setData({
      printMode: 1
    })
  },
  onDeviceChanged(e) {
    console.log(`--------- onDeviceChanged: ${e.detail.value} ------------`);
    this.setData({ deviceIndex: e.detail.value });
  },
  onOrientationChanged(e) {
    console.log(`--------- onOrientationChanged: ${e.detail.value} ------------`);
    this.setData({ orientationIndex: e.detail.value });
  },
  onGapTypeChanged(e) {
    console.log(`--------- onGapTypeChanged: ${e.detail.value} ------------`);
    this.setData({ gapIndex: e.detail.value });
  },
  onDarknessChanged(e) {
    console.log(`--------- onDarknessChanged: ${e.detail.value} ------------`);
    this.setData({ darknessIndex: e.detail.value });
  },
  onSpeedChanged(e) {
    console.log(`--------- onSpeedChanged: ${e.detail.value} ------------`);
    this.setData({ speedIndex: e.detail.value });
  },
  onPrintModeChanged(e) {
    console.log(`--------- onPrintModeChanged: ${e.detail.value} ------------`);
    this.setData({ printMode: e.detail.value });
  },
  initApi(canvas) {
    this.lpapi = LPAPIFactory.getInstance({
      // 日志信息显示级别，值为 0 - 4，0表示不显示调试信息，4表示显示所有调试信息
      showLog: 4,
      canvas: canvas,
      // 用于进行标签绘制的画布ID
      canvasId: this.data.canvasId,
    });
    // 搜索蓝牙设备
    this.lpapi.startBleDiscovery({
      timeout: 0,
      deviceFound: (devices) => {
        this.onDeviceFound(devices);
      },
    });
  },
  startDiscovery() {
    wx.showLoading({
      title: "正在搜索打印机...",
    });
    this.lpapi.startBleDiscovery({
      timeout: 5000,
      deviceFound: (devices) => {
        this.onDeviceFound(devices);
      },
      adapterStateChange: (result) => {
        if (!result.discovering) {
          wx.hideLoading();
        }
      },
    });
  },
  stopDiscovery() {
    this.lpapi.stopBleDiscovery();
  },
  getDevice() {
    return this.data.deviceList[this.data.deviceIndex];
  },
  openPrinter(callback) {
    const currDevice = this.getDevice();
    if (currDevice && currDevice.deviceId) {
      wx.showLoading({
        title: "正在链接打印机...",
      });
      this.lpapi.openPrinter({
        name: currDevice.name,
        deviceId: currDevice.deviceId,
        success: (resp) => {
          console.log(`---- 【打印机链接成功】`);
          wx.hideLoading();
          wx.showToast({ title: "打印机链接成功！", icon: "success" });
          if (typeof callback === "function") {
            callback(true);
          }
        },
        fail: (resp) => {
          console.warn(`---- 【打印机链接失败】`);
          console.warn(JSON.stringify(resp));
          wx.hideLoading();
          wx.showToast({ title: "打印机链接失败！", icon: "fail" });
          if (typeof callback === "function") {
            callback(false);
          }
        },
      });
    } else {
      console.warn("---- 未检测到打印机！");
      wx.showToast({ title: "未检测到打印机", icon: "fail" });
      if (typeof callback === "function") {
        callback(false);
      }
    }
  },
  closePrinter() {
    console.log(`---- 关闭打印机！`);
    this.lpapi.closePrinter();
  },
  onDeviceFound(devices) {
    console.log(`---- 检测到打印机：`);
    console.log(devices);
    for (const item of devices) {
      console.log(`-----------------------:`);
      console.log(item);
      // advertisData
      // serviceData
      const advertisData = new Uint8Array(item.advertisData);
      // console.log(`advertisData: [${advertisData.map(val => `00${val.toString(16)}`.slice(-2)).join(',')}]`);
      console.log(`advertisData: [${LPAUtils.getHexStringOfBytes(advertisData)}]`);
      if (item.serviceData) {
        console.log(`------- show serviceData:`);
        for (const key in item.serviceData) {
          console.log(`serviceData.key = ${key}`);
          // if (Object.hasOwnProperty.call(item.serviceData, key)) {
          //     const element = item.serviceData[key];
          // }
        }
      }
      // const serviceData = item.serviceData;
      // if(typeof serviceData.toString === "function") {
      //     console.log(serviceData.toString());
      // }
      // if(typeof serviceData.valueOf === "function") {
      //     console.log(serviceData.valueOf());
      // }
    }
    if (devices && devices.length > 0) {
      this.setData({
        deviceList: devices,
      });
    }
  },
  getJobName() {
    if (this.data.printMode > 0) {
      // return "#!#transparent#!#";
      return "#!#preview#!#";
    } else {
      return "lpapi-ble";
    }
  },
  getOrientation() {
    return this.data.orientationList[this.data.orientationIndex].value;
  },
  getGapType() {
    return this.data.gapList[this.data.gapIndex].value;
  },
  getPrintDarkness() {
    return this.data.darknessList[this.data.darknessIndex].value;
  },
  getPrintSpeed() {
    return this.data.speedList[this.data.speedIndex].value;
  },
  getThreshold() {
    return Number(this.data.threshold);
  },
  /**
   * @returns {Promise<boolean>}
   */
  checkAndOpenPrinter(callback) {
    return new Promise((resolve) => {
      if (this.data.printMode > 0) {
        // 预览模式不需要链接打印机
        callback && callback(true);
        resolve(true);
      } else {
        // 打印模式自动链接打印机
        this.openPrinter((res) => {
          callback && callback(res);
          resolve(res);
        });
      }
    });
  },
  previewLabel(result) {
    if (result.statusCode === 0 && Array.isArray(result.dataUrls)) {
      console.log(`---- 打印/预览成功！`);
      const imageList = result.dataUrls.map((v) => {
        return {
          value: v,
          key: `${Math.random()}`,
        };
      });
      this.setData({
        previewList: imageList,
      });
    } else {
      console.warn(`---- 打印/预览失败， statusCode = ${result.statusCode}`);
      console.warn(result);
    }
  },
  clearPreview() {
    this.setData({
      previewList: [],
    });
  },
  appendPreview(result) {
    const oldList = this.data.previewList;
    if (result.dataUrl) {
      oldList.push({
        value: result.dataUrl,
        key: `${Math.random()}`,
      });
      this.setData({
        previewList: oldList,
      });
    }
  },
  textPrintTest() {

    let order = {
      "code": "0070",
      "barCode": "00000126",
      "orderNo": "ORD20250117124826000001260070",
      "userInfo": {
        "id": 0,
        "username": "ljw",
        "phone": 17853441627,
        "avatar": "file-1737049578304-183682261.png",
        "sex": 0,
        "birthday": "2025-01-16",
        "address": "",
        "openId": "oZtzw6x2nLusjna_BCnEsdAV80KQ",
        "token": "KKyE90zKAzMBBMBBFBBKKyE91BFAwKKyE81BFAwKKyKVBFAxKKyE81BMBBFBCKKyKzAMBBFBCKKyFLBFBBKKyKLBFAzKLeKAyKAzNBBFBAFKyVKzKAzFBAKAyKLBMBBFAzKLeKBeKAyE91BMBBFBCKLeKAyKLBFAxKKyKLBFBFKBeKKyKAzFBxFMFFMBFMMFLAFKyKBAFBAFKyM90yMfeKAyKVBFBiFBNFBwFMLFLRFCGFLPFBOFBBKyyOyyU60zUUzVKzVezMoyU60zE81BFCQFLAKKyVyzV80zVUzN80yU70zKAzNBBFBAFKyO80zMKyU60zO90zU80zU70zKAzFBAKBeKBeKKyKAzFBwFMBFLAFKyFKyE90z",
        "isVIP": 0,
        "vipEndTime": "",
        "vipStatus": 0,
        "isAdmin": 1,
        "status": 0,
        "balance": 99910,
        "isDeleted": 0,
        "createdAt": "2025-01-16T17:46:18.000Z",
        "updatedAt": "2025-01-17T04:48:20.000Z",
        "isSAdmin": 0,
        "vipCode": "KpAF0",
        "coupons": [],
        "couponNum": 0,
        "balance_read": "999.10",
        "vipRights": {
          "act": 0,
          "pro": 0
        }
      },
      "totalPricePrint": "0.01",
      "address": "堂食",
      "paidAt": "2025-01-17 12:48:25",
      "proNum": 1,
      "items": [
        {
          "id": 260,
          "userId": 0,
          "orderNo": "ORD20250117124826000001260070",
          "status": 1,
          "totalPrice": 1,
          "currentPrice": 1,
          "currentPriceWithOptionsAndNum": 1,
          "currentPriceWithDiscount": 1,
          "address": "堂食",
          "isPro": 1,
          "itemId": 22,
          "itemInfo": {
            "id": 22,
            "title": "爱尔兰咖啡",
            "subTitle": "",
            "price": 1,
            "category1": "咖啡",
            "category2": "其他",
            "count": 975,
            "isAvailable": 1,
            "imageUrl": [
              "file-1737080006966-975462404.webp"
            ],
            "options": [],
            "content": "",
            "isVipAvailable": 1,
            "isCardAvailable": 1,
            "takeOutAvailable": 1,
            "soldOut": 25,
            "createdAt": "2025-01-17T02:13:27.000Z",
            "updatedAt": "2025-01-17T04:09:50.000Z",
            "priceDisplay": "0.01",
            "createdAt_read": "今天上午 10:13 星期五",
            "updatedAt_read": "今天中午 12:09 星期五",
            "optionsPreview": "",
            "discountPreview": "PLUS会员 优惠券 "
          },
          "options": {},
          optionsPrint: "温度:热|附加:巧克力",
          "discountType": 0,
          "paidAt": "2025-01-17T04:48:25.000Z",
          "createdAt": "2025-01-17T04:48:26.000Z",
          "updatedAt": "2025-01-17T04:48:26.000Z",
          "index": 1,
          "phone": 17853441627,
          "text": "",
          "printed": 0,
          "pricePrint": "0.01",
          "priceWithDiscountPrint": "0.01"
        }
      ]
    }

    const printOrderLabelData = []
    for (let i = 0; i < order.items.length; i++) {
      let currentItem = JSON.parse(JSON.stringify(order.items[i]))
      let order_c = JSON.parse(JSON.stringify(order))
      delete order_c.items
      delete order_c.userInfo
      printOrderLabelData.push({
        ...order_c,
        item: currentItem
      })
    }

    const api = this.lpapi;
    const labelWidth = 40;
    const labelHeight = 30;
    const padding = 2

    for (let i = 0; i < printOrderLabelData.length; i++) {
      let currentOrder = printOrderLabelData[i]

      this.checkAndOpenPrinter(async () => {
        let pos = 0;
        api.startJob({
          width: labelWidth,
          height: labelHeight,
          jobName: this.getJobName(),
        });
        if (currentOrder.item.index == 1) {
          api.drawLine({
            x1: 0,
            y1: 1,
            x2: labelWidth,
            y2: 1,
            lineWidth: 0.2,
          });
        }
        api.draw1DBarcode({
          text: order.barCode,
          x: padding,
          y: padding,
          width: labelWidth - padding * 2,
          height: 4,
          textHeight: 2,
          type: 26,
        });
        api.drawText({
          text: `${order.code}-${i + 1}/${order.proNum}`,
          x: padding + 14,
          y: padding + 5.5,
          fontHeight: 4.5,
        });
        api.drawText({
          text: `本单共支付`,
          x: padding,
          y: padding + 5,
          fontHeight: 2,
        });
        api.drawText({
          text: `￥${currentOrder.totalPricePrint}`,
          x: padding,
          y: padding + 5 + 2.5,
          fontHeight: 2,
        });
        let tt = `${currentOrder.item.itemInfo.title} ${currentOrder.item.optionsPrint}`
        api.drawText({
          text: tt,
          x: padding,
          y: padding + 10.5,
          width: labelWidth - padding * 2,
          fontHeight: 2.5,
        });
        api.drawText({
          text: `${currentOrder.item.discount === undefined ? `` : `${currentOrder.item.discount} `}￥${currentOrder.item.priceWithDiscountPrint}
支付于${currentOrder.paidAt}
预留电话：${currentOrder.item.phone}|备注：${currentOrder.item.text}`,
          x: padding,
          y: padding + 10.5 + ((parseInt(tool.calculateStringWeight(tt)) / 14) + ((tool.calculateStringWeight(tt) % 14) ? 1 : 0)) * 2.5 + 1,
          width: labelWidth - padding * 2,
          fontHeight: 2,
        });

        // 1. 最简单的绘制方式：只需要指定绘制内容和字体高度即可，默认绘制在左上角，字体高度为3毫米；
        // api.drawText({
        //   text: text1,
        //   fontHeight: 3,
        // });
        // // 分割线
        // pos += cellHeight;
        // api.drawLine({
        //   x1: 0,
        //   y1: pos,
        //   x2: labelWidth,
        //   y2: pos,
        //   lineWidth: 0.3,
        // });
        api.commitJob({
          gapType: this.getGapType(),
          darkness: this.getPrintDarkness(),
        }).then((resp) => {
          console.log(1234)
          this.previewLabel(resp);
        });
      });
    }

  },
  qrcodePrintTest(data, callback) {
    const api = this.lpapi;
    const labelWidth = 40;
    const labelHeight = 30;
    const margin = 2;
    // 二维码底部文本的高度
    const textHeight = 4;
    // 二维码大小
    const codeWidth = labelHeight - margin * 2 - textHeight;
    const text = typeof data === "string" ? data : "8888888888888888";
    //
    this.checkAndOpenPrinter(() => {
      // 创建 40mm x 30mm 大小的标签纸
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        jobName: this.getJobName(),
      });
      // 绘制二维码
      api.draw2DQRCode({
        text: text,
        x: (labelWidth - codeWidth) * 0.5,
        y: margin,
        width: codeWidth,
      });
      // 以文本形式，将二维码内容绘制到二维码底部
      api.drawText({
        text: text,
        x: 0,
        y: margin + codeWidth,
        width: labelWidth,
        height: textHeight,
        fontHeight: 3.5,
        horizontalAlignment: this.isLark ? 0 : 1,
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
        // 执行打印完毕回调函数
        if (typeof callback === "function") {
          callback(true);
        }
      });
    });
  },
  pdf417PrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 40;
    const labelHeight = 30;
    const margin = 2;
    const text = "上海道臻信息技术有限公司";
    const textHeight = 4;
    const codeHeight = labelHeight - margin * 2 - textHeight;
    //
    this.checkAndOpenPrinter(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        jobName: this.getJobName(),
      });
      //
      api.draw2DPdf417({
        text: text,
        x: margin,
        y: margin,
        width: labelWidth - margin * 2,
        height: codeHeight,
      });
      //
      api.drawText({
        text: text,
        x: 0,
        y: margin + codeHeight,
        width: labelWidth,
        height: textHeight,
        fontHeight: 3.5,
        horizontalAlignment: this.isLark ? 0 : 1,
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
      });
    });
  },
  dataMatrixPrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 40;
    const labelHeight = 30;
    const textHeight = 4;
    const margin = 2;
    const codeWidth = labelHeight - margin * 2 - textHeight;
    const text = "上海道臻信息技术有限公司";
    //
    this.checkAndOpenPrinter(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        jobName: this.getJobName(),
      });
      api.draw2DDataMatrix({
        text: text,
        x: (labelWidth - codeWidth) * 0.5,
        y: margin,
        width: codeWidth,
        height: codeWidth,
      });
      api.drawText({
        text: text,
        x: 0,
        y: margin + codeWidth,
        width: labelWidth,
        height: textHeight,
        fontHeight: 3.5,
        horizontalAlignment: this.isLark ? 0 : 1,
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
      });
    });
  },
  barcodePrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 40;
    const labelHeight = 30;
    const margin = 2;
    //
    this.checkAndOpenPrinter(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        jobName: this.getJobName(),
      });
      // 绘制外边框
      api.drawRectangle({
        width: labelWidth,
        height: labelHeight,
      });
      api.draw1DBarcode({
        text: "12345678",
        x: margin,
        y: margin,
        width: labelWidth - margin * 2,
        height: labelHeight - margin * 2,
        textHeight: 5,
        type: 22,
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
      });
    });
  },
  localImagePrintTest() {
    const api = this.lpapi;
    const labelWidth = 40;
    const labelHeight = 40;
    const margin = 2;
    const url = "/static/yinlifun.png";
    //
    this.checkAndOpenPrinter(() => {
      api.loadImage(url, (image) => {
        api.startJob({
          width: labelWidth,
          height: labelHeight,
          jobName: this.getJobName(),
        });
        // 绘制标签外边框
        api.drawRectangle({
          width: labelWidth,
          height: labelHeight,
          lineWidth: 0.3,
        });
        // 绘制图片
        api.drawImage({
          image: image,
          x: margin,
          y: margin,
          width: labelWidth - margin * 2,
          height: labelHeight - margin * 2,
        });
        //
        api.commitJob({
          gapType: this.getGapType(),
          darkness: this.getPrintDarkness(),
          threshold: this.getThreshold(),
        }).then((resp) => {
          this.previewLabel(resp);
        });
      });
    });
  },
  remoteImagePrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 30;
    const labelHeight = 30;
    const margin = 2;
    const url = "https://www.detonger.com/img/QRCode_OfficialAccounts.png";
    //
    this.checkAndOpenPrinter(() => {
      api.loadImage(url, (image) => {
        api.startJob({
          width: labelWidth,
          height: labelHeight,
          jobName: this.getJobName(),
        });
        // 绘制标签外边框
        api.drawRectangle({
          width: labelWidth,
          height: labelHeight,
          lineWidth: 0.3,
        });
        // 绘制图片
        api.drawImage({
          image: image,
          x: margin,
          y: margin,
          width: labelWidth - margin * 2,
          height: labelHeight - margin * 2,
        });
        //
        api.commitJob({
          gapType: this.getGapType(),
          darkness: this.getPrintDarkness(),
          threshold: this.getThreshold(),
        }).then((resp) => {
          this.previewLabel(resp);
        });
      });
    });
  },
  rectanglePrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 40;
    const labelHeight = 30;
    const itemWidth = labelWidth * 0.5;
    const itemHeight = labelHeight * 0.5;
    const margin = 1;
    const padding = 2;
    const lineWidth = 0.3;
    //
    this.checkAndOpenPrinter(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        jobName: this.getJobName(),
      });
      // 绘制中间横线
      api.drawLine({
        x1: 0,
        y1: itemHeight,
        x2: labelWidth,
        y2: itemHeight,
        lineWidth: 0.3,
      });
      // 绘制中间竖线(绘制虚线)
      api.drawLine({
        x1: itemWidth,
        y1: 0,
        x2: itemWidth,
        y2: labelHeight,
        lineWidth: 0.3,
        dashLens: [1, 0.5],
      });
      //====================================================//
      //===== 常规矩形测试
      //====================================================//
      // 在左上角绘制矩形框
      api.drawRectangle({
        x: margin,
        y: margin,
        width: itemWidth - margin * 2,
        height: itemHeight - margin * 2,
        lineWidth: lineWidth,
      });
      // 左上角绘制填充矩形
      api.drawRectangle({
        x: margin + padding,
        y: margin + padding,
        width: itemWidth - (margin + padding) * 2,
        height: itemHeight - (margin + padding) * 2,
        fill: true,
      });
      //====================================================//
      //===== 圆角矩形测试
      //====================================================//
      // 在右上角绘制圆角矩形框
      api.drawRectangle({
        x: margin + itemWidth,
        y: margin,
        width: itemWidth - margin * 2,
        height: itemHeight - margin * 2,
        lineWidth: lineWidth,
        cornerWidth: 1.5,
      });
      // 左上角绘制填充矩形
      api.drawRectangle({
        x: margin + padding + itemWidth,
        y: margin + padding,
        width: itemWidth - (margin + padding) * 2,
        height: itemHeight - (margin + padding) * 2,
        fill: true,
        cornerWidth: 1.5,
      });
      //====================================================//
      //===== 椭圆测试
      //====================================================//
      // 在右上角绘制圆角矩形框
      api.drawEllipse({
        x: margin,
        y: margin + itemHeight,
        width: itemWidth - margin * 2,
        height: itemHeight - margin * 2,
        lineWidth: lineWidth,
      });
      // 左上角绘制填充矩形
      api.drawEllipse({
        x: margin + padding,
        y: margin + padding + itemHeight,
        width: itemWidth - (margin + padding) * 2,
        height: itemHeight - (margin + padding) * 2,
        fill: true,
      });
      //====================================================//
      //===== 正圆测试
      //====================================================//
      // 在右下角绘制圆形边框
      api.drawCircle({
        x: itemWidth * 1.5,
        y: itemHeight * 1.5,
        radius: Math.min(itemWidth, itemHeight) * 0.5 - margin,
      });
      // 左下角绘制填充圆形
      api.drawCircle({
        x: itemWidth * 1.5,
        y: itemHeight * 1.5,
        radius: Math.min(itemWidth, itemHeight) * 0.5 - margin - padding,
        fill: true,
      });
      // 提交任务
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
      });
    });
  },
  alignmentPrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 60;
    const labelHeight = 40;
    const itemWidth = labelWidth * 0.5;
    const itemHeight = labelHeight * 0.5;
    const text = "上海道臻信息技术有限公司";
    const fontHeight = 4;
    // 标签整体右转90度
    const orientation = 90;
    //
    this.checkAndOpenPrinter(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        orientation: orientation,
        jobName: this.getJobName(),
      });
      // 将正张标签分割成四个显示区域
      api.drawRectangle({
        x: 0,
        y: 0,
        width: labelWidth,
        height: labelHeight,
        lineWidth: 0.3,
      });
      api.drawLine({
        y1: itemHeight,
        x2: labelWidth,
        lineWidth: 0.3,
      });
      api.drawLine({
        x1: itemWidth,
        y2: labelHeight,
        lineWidth: 0.3,
      });
      // 水平居左，垂直居右对齐
      api.drawText({
        text: text,
        x: 0,
        y: 0,
        width: itemWidth,
        height: itemHeight,
        horizontalAlignment: 0,
        verticalAlignment: 0,
        fontHeight: fontHeight,
        // 常规字体样式
        fontStyle: 0,
      });
      // 水平居中，垂直居中
      api.drawText({
        text: text,
        x: itemWidth,
        y: 0,
        width: itemWidth,
        height: itemHeight,
        horizontalAlignment: 1,
        verticalAlignment: 1,
        fontHeight: fontHeight,
        // 字体样式：黑体
        fontStyle: 1,
      });
      // 水平居右，垂直居下
      api.drawText({
        text: text,
        x: itemWidth,
        y: itemHeight,
        width: itemWidth,
        height: itemHeight,
        horizontalAlignment: 2,
        verticalAlignment: 2,
        fontHeight: fontHeight,
        // 字体样式：斜体
        fontStyle: 2,
      });
      // 水平拉伸，垂直拉伸
      api.drawText({
        text: text,
        x: 0,
        y: itemHeight,
        width: itemWidth,
        height: itemHeight,
        horizontalAlignment: 3,
        verticalAlignment: 3,
        fontHeight: fontHeight,
        // 字体样式：粗斜体
        fontStyle: 3,
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
      });
    });
  },
  rotationPrintTest() {
    const api = this.lpapi
    function printOrderReceipt(order) {
      // Initialize lpapi instance

      api.startDrawLabel('80mm', '50mm', 0);

      // Title Section
      api.setItemOrientation(0);
      api.drawText('订单信息', 4, 2, {
        fontSize: 12,
        fontWeight: 'bold',
        textAlign: 'center',
      });

      // Order Number
      api.drawText(`订单号: ${order.orderId}`, 2, 8, {
        fontSize: 10,
      });

      // User Info
      api.drawText(`用户: ${order.customerName}`, 2, 12, {
        fontSize: 10,
      });
      api.drawText(`电话: ${order.customerPhone}`, 2, 16, {
        fontSize: 10,
      });

      // Address
      api.drawText(`地址: ${order.deliveryAddress}`, 2, 20, {
        fontSize: 10,
        textAlign: 'left',
      });

      // Line Divider
      api.drawLine(2, 24, 76, 24, 1);

      // Items Section
      let currentY = 28;
      api.drawText('商品列表:', 2, currentY, {
        fontSize: 10,
      });
      currentY += 4;

      order.items.forEach(item => {
        api.drawText(`${item.name} x${item.quantity} - ￥${item.price}`, 2, currentY, {
          fontSize: 10,
        });
        currentY += 4;
      });

      // Total Price and Discount
      api.drawLine(2, currentY, 76, currentY, 1);
      currentY += 4;

      api.drawText(`总价: ￥${order.totalPrice}`, 2, currentY, {
        fontSize: 10,
      });
      currentY += 4;

      api.drawText(`折扣: ￥${order.discount}`, 2, currentY, {
        fontSize: 10,
      });
      currentY += 4;

      api.drawText(`实际支付: ￥${order.finalPrice}`, 2, currentY, {
        fontSize: 10,
        fontWeight: 'bold',
      });
      currentY += 8;

      // Footer Section
      api.drawText('感谢您的惠顾！', 4, currentY, {
        fontSize: 10,
        textAlign: 'center',
      });

      api.endDrawLabel();
      api.print();
    }

    const order = {
      orderId: '12345678',
      customerName: '张三',
      customerPhone: '13800000000',
      deliveryAddress: '北京市朝阳区某街道某小区',
      items: [
        { name: '商品A', quantity: 1, price: 50 },
        { name: '商品B', quantity: 2, price: 30 },
      ],
      totalPrice: 110,
      discount: 10,
      finalPrice: 100,
    };

    printOrderReceipt(order)
    return
    // const api = this.lpapi;
    //
    const labelWidth = 60;
    const labelHeight = 40;
    const itemWidth = labelWidth * 0.5;
    const itemHeight = labelHeight * 0.5;
    const orientation = 90;
    const text = "上海道臻信息技术有限公司";
    //
    this.checkAndOpenPrinter(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        orientation: orientation,
        jobName: this.getJobName(),
      });
      // 将整个打印区域分割成四个区域，分别进行四种旋转测试
      api.drawRectangle({
        width: labelWidth,
        height: labelHeight,
        lineWidth: 0.3,
      });
      api.drawLine({
        y: itemHeight,
        width: labelWidth,
        height: 0.3,
      });
      api.drawLine({
        x: itemWidth,
        width: 0.3,
        height: labelHeight,
      });
      //
      api.drawText({
        text: text,
        x: 0,
        y: 0,
        width: itemWidth,
        height: itemHeight,
        // 0：表示不旋转
        orientation: 0,
        fontHeight: 4,
      });
      //
      api.drawText({
        text: text,
        x: itemWidth,
        y: 0,
        width: itemWidth,
        height: itemHeight,
        // 90：表示右转90度
        orientation: 90,
        fontHeight: 4,
      });
      //
      api.drawText({
        text: text,
        x: itemWidth,
        y: itemHeight,
        width: itemWidth,
        height: itemHeight,
        // 180：表示旋转180度
        orientation: 180,
        fontHeight: 4,
      });
      //
      api.drawText({
        text: text,
        x: 0,
        y: itemHeight,
        width: itemWidth,
        height: itemHeight,
        // 270：表示左转90度
        orientation: 270,
        fontHeight: 4,
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
      });
    });
  },
  tablePrintTest() {
    const api = this.lpapi;
    //
    const labelWidth = 60;
    const labelHeight = 40;
    const margin = 1.5;
    //
    return this.checkAndOpenPrinter().then(() => {
      api.startJob({
        width: labelWidth,
        height: labelHeight,
        orientation: this.getOrientation(),
        jobName: this.getJobName(),
      });
      // 将整个打印区域分割成四个区域，分别进行四种旋转测试
      api.drawTable({
        x: margin,
        y: margin,
        width: labelWidth - margin * 2,
        height: labelHeight - margin * 2,
        rows: 3,
        columns: 3,
        lineWidth: 0.4,
        // 指定单元格的宽度，未指定或者小于1表示按照一定的比例分配剩余空间
        columnWidths: [18, 0, 25],
        horizontalAlignment: 0,
        cells: [
          {
            type: "text",
            text: "表格打印测试",
            fontStyle: 1,
            fontHeight: 3.5,
            columnSpan: 3,
            horizontalAlignment: 1,
          },
          "",
          "",
          "设备名称",
          "打印机",
          {
            type: "qrcode",
            text: "8888888888",
            rowSpan: 2,
          },
          "设备型号",
          "DT60",
          "",
        ],
      });
      //
      api.commitJob({
        gapType: this.getGapType(),
        darkness: this.getPrintDarkness(),
      }).then((resp) => {
        this.previewLabel(resp);
        return resp.statusCode === 0;
      });
    });
  },
  jsonPrintTest() {
    const device = this.getDevice() || {};
    // 有个问题：无法更新画布大小
    const api = this.lpapi;
    this.clearPreview();
    //
    api.print({
      jobInfo: {
        jobWidth: 40,
        jobHeight: 30,
        jobName: this.getJobName(),
        orientation: this.getOrientation(),
        gapType: this.getGapType(),
        printDarkness: this.getPrintDarkness(),
        printSpeed: this.getPrintSpeed(),
      },
      printerInfo: {
        name: device.name,
        deviceId: device.deviceId,
      },
      jobPages: [
        [
          // 第一张标签，打印一维码
          { type: "rect", x: 1.5, y: 1.5, width: 40 - 3, height: 30 - 3, lineWidth: 0.4 },
          {
            type: "barcode",
            x: 2,
            y: 6,
            width: 36,
            height: 22,
            textHeight: 5,
            barcodeType: 60,
            horizontalAlignment: 1,
            text: "www.dothantech.com",
          },
        ],
        [
          // 第二章标签，打印二维码
          { type: "rect", x: 1.5, y: 1.5, width: 40 - 3, height: 30 - 3, lineWidth: 0.4 },
          {
            type: "qrcode",
            x: 1.5,
            y: 2.5,
            width: 37,
            height: 20,
            horizontalAlignment: 1,
            text: "上海道臻信息技术有限公司",
          },
          {
            type: "text",
            x: 1.5,
            y: 23,
            width: 37,
            height: 5,
            fontHeight: 3,
            horizontalAlignment: 1,
            text: "上海道臻信息技术有限公司",
          },
        ],
      ],
      onPageComplete: (res) => {
        // 通过 pageComplete可以监控打印或者预览的进度。
        this.appendPreview(res);
        console.log(`----- 打印进度：[${res.pageIndex} / ${res.printPages}]`);
      },
    }).then((resp) => {
      if (resp.statusCode !== 0) {
        console.warn(`---- 打印失败，statusCode = ${resp.statusCode}`);
      } else {
        console.log(`---- 打印成功！`);
      }
      // this.previewLabel(resp);
    });
  },
  dataBindPrintTest() {
    const api = this.lpapi;
    const device = this.getDevice() || {};
    this.clearPreview();
    //
    api.print({
      jobInfo: {
        jobWidth: 50,
        jobHeight: 70,
        jobName: this.getJobName(),
        orientation: this.getOrientation(),
        gapType: this.getGapType(),
        printDarkness: this.getPrintDarkness(),
        printSpeed: this.getPrintSpeed(),
      },
      printerInfo: {
        name: device.name,
        deviceId: device.deviceId,
      },
      jobPage: [
        { type: "rect", x: 1, y: 1, width: 48, height: 68, lineWidth: 0.3 },
        {
          type: "text",
          // 打印内容可以通过 columnName 来绑定到 jobArguments 参数列表中相关数据
          columnName: "column1",
          x: 1,
          y: 1,
          width: 48,
          height: 68,
          fontHeight: 3,
        },
      ],
      jobArguments: [
        { column1: "1德佟印立方是一家集研发、生产、销售和技术服务于一体的专业标签打印机生产厂家，旗下拥有德佟电子和印立方两个不同系列的品牌。 公司创立于2016年，主要生产和销售移动便携式标签打印机及配套耗材，并为顾客量身定制标签标识解决方案。公司总部位于中国上海，并在广州和苏州张家港设立分公司。公司生产基地位于苏州张家港总面积为8000平，主要生产标签打印机及其使用耗材。公司虽然成立时间不长，但已推出多款标签打印机，突破产品研发壁垒，填补了市场产品空缺，推动便携式标签打印机市场发展。公司进入市场之后，凭借切合市场需求的产品、过硬的软硬件技术能力、良好的线上线下代理商合作模式， 已经成为该市场领域事实上的标杆领头羊，在保持和客户多方共赢的同时，自身销售额每年也在以超过50%的速度高速增长。业务已覆盖：通讯电力，政企教育，烟草管理，危废管理，商业零售，办公生活。" },
        { column1: "2德佟印立方是一家集研发、生产、销售和技术服务于一体的专业标签打印机生产厂家，旗下拥有德佟电子和印立方两个不同系列的品牌。 公司创立于2016年，主要生产和销售移动便携式标签打印机及配套耗材，并为顾客量身定制标签标识解决方案。公司总部位于中国上海，并在广州和苏州张家港设立分公司。公司生产基地位于苏州张家港总面积为8000平，主要生产标签打印机及其使用耗材。公司虽然成立时间不长，但已推出多款标签打印机，突破产品研发壁垒，填补了市场产品空缺，推动便携式标签打印机市场发展。公司进入市场之后，凭借切合市场需求的产品、过硬的软硬件技术能力、良好的线上线下代理商合作模式， 已经成为该市场领域事实上的标杆领头羊，在保持和客户多方共赢的同时，自身销售额每年也在以超过50%的速度高速增长。业务已覆盖：通讯电力，政企教育，烟草管理，危废管理，商业零售，办公生活。" },
        { column1: "3德佟印立方是一家集研发、生产、销售和技术服务于一体的专业标签打印机生产厂家，旗下拥有德佟电子和印立方两个不同系列的品牌。 公司创立于2016年，主要生产和销售移动便携式标签打印机及配套耗材，并为顾客量身定制标签标识解决方案。公司总部位于中国上海，并在广州和苏州张家港设立分公司。公司生产基地位于苏州张家港总面积为8000平，主要生产标签打印机及其使用耗材。公司虽然成立时间不长，但已推出多款标签打印机，突破产品研发壁垒，填补了市场产品空缺，推动便携式标签打印机市场发展。公司进入市场之后，凭借切合市场需求的产品、过硬的软硬件技术能力、良好的线上线下代理商合作模式， 已经成为该市场领域事实上的标杆领头羊，在保持和客户多方共赢的同时，自身销售额每年也在以超过50%的速度高速增长。业务已覆盖：通讯电力，政企教育，烟草管理，危废管理，商业零售，办公生活。" },
        { column1: "4德佟印立方是一家集研发、生产、销售和技术服务于一体的专业标签打印机生产厂家，旗下拥有德佟电子和印立方两个不同系列的品牌。 公司创立于2016年，主要生产和销售移动便携式标签打印机及配套耗材，并为顾客量身定制标签标识解决方案。公司总部位于中国上海，并在广州和苏州张家港设立分公司。公司生产基地位于苏州张家港总面积为8000平，主要生产标签打印机及其使用耗材。公司虽然成立时间不长，但已推出多款标签打印机，突破产品研发壁垒，填补了市场产品空缺，推动便携式标签打印机市场发展。公司进入市场之后，凭借切合市场需求的产品、过硬的软硬件技术能力、良好的线上线下代理商合作模式， 已经成为该市场领域事实上的标杆领头羊，在保持和客户多方共赢的同时，自身销售额每年也在以超过50%的速度高速增长。业务已覆盖：通讯电力，政企教育，烟草管理，危废管理，商业零售，办公生活。" },
        { column1: "5德佟印立方是一家集研发、生产、销售和技术服务于一体的专业标签打印机生产厂家，旗下拥有德佟电子和印立方两个不同系列的品牌。 公司创立于2016年，主要生产和销售移动便携式标签打印机及配套耗材，并为顾客量身定制标签标识解决方案。公司总部位于中国上海，并在广州和苏州张家港设立分公司。公司生产基地位于苏州张家港总面积为8000平，主要生产标签打印机及其使用耗材。公司虽然成立时间不长，但已推出多款标签打印机，突破产品研发壁垒，填补了市场产品空缺，推动便携式标签打印机市场发展。公司进入市场之后，凭借切合市场需求的产品、过硬的软硬件技术能力、良好的线上线下代理商合作模式， 已经成为该市场领域事实上的标杆领头羊，在保持和客户多方共赢的同时，自身销售额每年也在以超过50%的速度高速增长。业务已覆盖：通讯电力，政企教育，烟草管理，危废管理，商业零售，办公生活。" },
      ],
      onPageComplete: (res) => {
        // 通过 pageComplete可以监控打印或者预览的进度。
        this.appendPreview(res);
        console.log(`----- 打印进度：[${res.pageIndex} / ${res.printPages}]`);
      },
    }).then((resp) => {
      if (resp.statusCode !== 0) {
        console.warn(`---- 打印失败，statusCode = ${resp.statusCode}`);
      } else {
        console.log(`---- 打印成功！`);
      }
      // this.previewLabel(resp);
    });
  },
  wdfxPrintTest() {
    const device = this.getDevice() || {};
    // 清空预览列表
    this.clearPreview();
    //
    this.lpapi.printWdfx({
      domParser: new DOMParser(),
      content: wdfxStr,
      jobInfo: {
        jobName: this.getJobName(),
        orientation: this.getOrientation(),
        gapType: this.getGapType(),
        printDarkness: this.getPrintDarkness(),
        printSpeed: this.getPrintSpeed(),
      },
      printerInfo: {
        name: device.name,
        deviceId: device.deviceId,
      },
      onPageComplete: (res) => {
        // 通过 pageComplete可以监控打印或者预览的进度。
        // this.previewLabel(res);
        this.appendPreview(res);
        console.log(`----- 打印进度：[${res.pageIndex} / ${res.printPages}]`);
      },
    }).then((resp) => {
      if (resp.statusCode !== 0) {
        console.warn(`---- 打印失败，statusCode = ${resp.statusCode}`);
      } else {
        console.log(`---- 打印成功！`);
      }
      // this.previewLabel(resp);
    });
  },
  async imagesPrintTest(url) {
    const api = this.lpapi;
    //
    const labelWidth = 40;
    const labelHeight = 40;
    const margin = 2;
    //
    const image = await api.loadImage(url);
    api.startJob({
      width: labelWidth,
      height: labelHeight,
      jobName: this.getJobName(),
    });
    // 绘制标签外边框
    api.drawRectangle({
      width: labelWidth,
      height: labelHeight,
      lineWidth: 0.3,
    });
    // 绘制图片
    api.drawImage({
      image: image,
      x: margin,
      y: margin,
      width: labelWidth - margin * 2,
      height: labelHeight - margin * 2,
    });
    //
    const resp = await api.commitJob({
      gapType: this.getGapType(),
      darkness: this.getPrintDarkness(),
    });
    this.previewLabel(resp);
    return true;
  },
  /**
   * 循环打印方式1，通过嵌套调用来实现。
   *
   * @param {Object[]} list 打印数据列表
   * @param {number} index 当前打印数据的索引
   * @param {(result: any) => void} 打印结果回调函数
   */
  printQrcodePages(list, index, callback) {
    if (index >= list.length) {
      console.log(`------ 打印完毕！ -------`);
      if (callback) {
        callback("打印完毕！");
      }
    } else {
      // 未打印完毕，则继续打印下一张标签
      this.qrcodePrintTest(list[index], () => {
        console.log(`------ 打印进度：[${index + 1} / ${list.length}]`);
        this.printPages1(list, index + 1, callback);
      });
    }
  },
  async multiPagePrintTest() {
    const imageList = [
      "/static/yinlifun.png",
      "https://www.detonger.com/img/QRCode_OfficialAccounts.png",
      "/static/yinlifun.png",
      "https://www.detonger.com/img/QRCode_OfficialAccounts.png",
      "/static/yinlifun.png",
    ];
    // 链接打印机
    const res = await this.checkAndOpenPrinter();
    if (!res) {
      console.warn(`---- 打印机打开失败！`);
      wx.showToast({ title: "打印机链接失败！", icon: "error" });
      return;
    }
    // 循环打印
    for (let i = 0; i < imageList.length; i++) {
      await this.imagesPrintTest(imageList[i]);
      console.log(`------ 打印进度：[${i + 1} / ${imageList.length}]`);
    }
    console.log(`------ 打印完毕! -------`);
  },
});
